const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let name 		= req.body.name;
	let price 		= req.body.price;
	let introduce 	= req.body.introduce;
	let imgurl 		= req.body.imgurl || '/img/default-pill.jpg';
	let producetime = req.body.producetime;
	let abletime 	= req.body.abletime;
	let code		= req.body.code;
	let company 	= req.body.company;
	let address 	= req.body.address;
	let phone 		= req.body.phone;
	let type		= req.body.type;

	if (name == undefined || price == undefined || introduce == undefined || producetime == undefined || abletime == undefined || code == undefined || company == undefined || address == undefined || phone == undefined || type == undefined) {
		sendResponse('error','参数缺失', null, res);
		return;
	}

	pool.getConnection(function(err, connection) {
		if (err) { 
			sendResponse('error','数据库错误', null, res);
			return;
		}
		let params = [name, price, introduce, imgurl, producetime, abletime, code, company, address, phone, type];
		connection.query('INSERT INTO medicine (name, price, introduce, imgurl, producetime, abletime, code, company, address, phone, type) VALUES (?,?,?,?,?,?,?,?,?,?,?);', params, function (error, rows, fields) {

			connection.release();

			if (error) { 
				console.log(error)
				if (error.code = "ER_DUP_ENTRY") {
					sendResponse('error','修改重复', null, res);
					return;
				} else {
					sendResponse('error','数据库错误', null, res);
					return;
				}
			} else {
				sendResponse('ok', '修改成功', null, res);
				return;
			}

		})	

	});

}